package Game

import (
	"GameGo/config"
	"GameGo/po"
	"GameGo/tool"
	"fmt"
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/text"
	"image/color"
	"log"
)

type Game struct {
	po.Game
}

func (g *Game) Update() error {
	switch g.State {
	case po.StateStart:
		if ebiten.IsKeyPressed(ebiten.KeySpace) || ebiten.IsKeyPressed(ebiten.KeyEnter) {
			g.resetGame()
			g.State = po.StatePlaying
		}
		g.Bgm.Pause()
	case po.StatePlaying:
		if !g.Bgm.IsPlaying() {
			g.Bgm.Play()
		}
		UpdateGameLogic(g)
	case po.StateGameOver:
		g.Bgm.Pause()
		if ebiten.IsKeyPressed(ebiten.KeyR) {
			g.State = po.StateStart
		}
	case po.StateGameEnd:
		g.Bgm.Pause()
		if ebiten.IsKeyPressed(ebiten.KeyR) {
			g.State = po.StateStart
		}

	}

	return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
	switch g.State {
	case po.StateStart:
		x := config.ScreenXSize/2 - len("  飞机大战")*4
		y := config.ScreenXSize / 2
		texts := fmt.Sprintf("[空格] 开始游戏")
		text.Draw(screen, "飞机大战", tool.GetFont(50), 40, y, color.White)
		text.Draw(screen, texts, tool.GetFont(8), x-10, y+100, color.White)
	case po.StatePlaying:
		DrawGame(screen, g)
	case po.StateGameOver:
		x := config.ScreenXSize/2 - len("GAME OVER!")*4
		y := config.ScreenXSize / 2
		texts := fmt.Sprintf("分数: %d \n用时: %d秒\n击杀率: %.2f%%\n[R] 返回",
			g.Score, g.StartTime/60, float64(g.Score)/float64(g.EnemyScore)*100)
		text.Draw(screen, "GAME OVER!", tool.GetFont(40), 40, y, color.White)
		text.Draw(screen, texts, tool.GetFont(12), x, y+100, color.White)
	case po.StateGameEnd:
		x := config.ScreenXSize/2 - len("恭喜通关!")*4
		y := config.ScreenXSize / 2
		texts := fmt.Sprintf("分数: %d \n用时: %d秒\n击杀率: %.2f%%\n[R] 返回",
			g.Score, g.StartTime/60, float64(g.Score)/float64(g.EnemyScore)*100)
		text.Draw(screen, "恭喜通关!", tool.GetFont(40), 60, y, color.White)
		text.Draw(screen, texts, tool.GetFont(12), x, y+100, color.White)
	}
}

func (g *Game) Layout(outsideWidth, outsideHeight int) (int, int) {
	return config.ScreenXSize, config.ScreenYSize
}

func (g *Game) resetGame() {
	g.PlayerHP = config.PlayerHP
	g.PlayerMaxHP = config.PlayerHP
	g.PlayerMaxExp = config.PlayerExp
	g.PlayerExp = 0
	g.PlayerLevel = 1
	g.EnemyNum = []int{config.OrdinaryEnemy, config.EliteEnemy, config.Boss}
	g.PlayerX = config.ScreenXSize/2 - float64(g.PlayerImg.Bounds().Dx())/2
	g.PlayerY = config.ScreenYSize
	g.Score = 0
	g.Bullets = nil
	g.Enemies = nil
	g.EnemyTimer = 0
	g.EnemyScore = 0
	g.ShootCooldown = 0
	g.GameLevel = 1
}

func Start() {

	ebiten.SetWindowSize(config.ScreenXSize, config.ScreenYSize)
	ebiten.SetWindowTitle("飞机大战")

	game := &Game{*InitGame()}
	if err := ebiten.RunGame(game); err != nil {
		log.Fatal(err)
	}
}
